package com.dd.admin.system.setting.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.admin.common.model.PageFactory;
import com.dd.admin.system.setting.domain.SystemSettingDto;
import com.dd.admin.system.setting.domain.SystemSettingVo;
import com.dd.admin.system.setting.entity.SystemSetting;
import com.dd.admin.system.setting.mapper.SystemSettingMapper;
import com.dd.admin.system.setting.service.SystemSettingService;
import com.dd.admin.common.service.MinioService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 系统设置 服务实现类
 * </p>
 *
 * @author 727869402@qq.com
 * @since 2024-12-01
 */
@Service
public class SystemSettingServiceImpl extends ServiceImpl<SystemSettingMapper, SystemSetting> implements SystemSettingService {

    @Value("${dd.storage-mode:local}")
    private String defaultStorageMode;

    @Autowired
    private MinioService minioService;

    @Override
    public IPage<SystemSettingVo> selectSystemSettingPage(SystemSettingDto systemSettingDto) {
        Page page = PageFactory.defaultPage();
        return baseMapper.selectSystemSettingPage(page, systemSettingDto);
    }

    @Override
    public List<SystemSettingVo> selectSystemSettingList(SystemSettingDto systemSettingDto) {
        return baseMapper.selectSystemSettingList(systemSettingDto);
    }

    @Override
    public String getSettingValue(String settingKey) {
        return getSettingValue(settingKey, null);
    }

    @Override
    public String getSettingValue(String settingKey, String defaultValue) {
        QueryWrapper<SystemSetting> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("SETTING_KEY", settingKey)
                   .eq("IS_ENABLED", true)
                   .last("LIMIT 1");
        
        SystemSetting setting = getOne(queryWrapper);
        if (setting != null && setting.getSettingValue() != null) {
            return setting.getSettingValue();
        }
        return defaultValue;
    }

    @Override
    public boolean setSetting(String settingKey, String settingValue, String settingDesc) {
        QueryWrapper<SystemSetting> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("SETTING_KEY", settingKey);
        
        SystemSetting existingSetting = getOne(queryWrapper);
        if (existingSetting != null) {
            // 更新现有设置
            existingSetting.setSettingValue(settingValue);
            if (settingDesc != null) {
                existingSetting.setSettingDesc(settingDesc);
            }
            existingSetting.setIsEnabled(true);
            return updateById(existingSetting);
        } else {
            // 创建新设置
            SystemSetting newSetting = new SystemSetting();
            newSetting.setSettingKey(settingKey);
            newSetting.setSettingValue(settingValue);
            newSetting.setSettingDesc(settingDesc);
            newSetting.setSettingType("SYSTEM");
            newSetting.setIsEnabled(true);
            return save(newSetting);
        }
    }

    @Override
    public String getStorageMode() {
        String storageMode = getSettingValue("STORAGE_MODE");
        return storageMode != null ? storageMode : defaultStorageMode;
    }

    @Override
    public boolean setStorageMode(String storageMode) {
        return setSetting("STORAGE_MODE", storageMode, "文件存储模式：local(本地存储) 或 minio(MinIO对象存储)");
    }

    @Override
    public String getSmsMode() {
        String smsMode = getSettingValue("SMS_MODE");
        return smsMode != null ? smsMode : "test";
    }

    @Override
    public boolean setSmsMode(String smsMode) {
        return setSetting("SMS_MODE", smsMode, "短信发送模式：test(测试模式) 或 real(真实发送)");
    }

    @Override
    public boolean checkMinioConnectivity() {
        try {
            // 尝试调用MinIO服务的连通性检查方法
            return minioService.checkConnection();
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean validateAndSetStorageMode(String storageMode) {
        // 如果要切换到MinIO，先检查连通性
        if ("minio".equalsIgnoreCase(storageMode)) {
            if (!checkMinioConnectivity()) {
                return false; // MinIO不可连通，不允许切换
            }
        }
        
        // 连通性检查通过或者是本地存储模式，执行设置
        return setStorageMode(storageMode);
    }

}